//
//  KSTempListVC.swift
//  ZYA
//
//  Created by 邱仙凯 on 2022/7/11.
//  Copyright © 2025 aowang. All rights reserved.
//


import UIKit
// MARK: -- 按钮事件
extension KSTempListVC {
    // 判断是否可编辑
    func judgeEditEnable(one:[String:Any]) -> Bool {
        if self.rootTemp.limitMakerModifyID != "" {
            let optid =  any2Str(one[self.rootTemp.limitMakerModifyID])
            // 为空也可以操作，认为无制单人，大家都可以操作
            if (optid == USERINFO.idKey.unwrap) || (optid == "") {
                return true
            } else {
                KSToast("非制单人不能做此操作!")
                return false
            }
        } else {
            return true
        }
    }
    
    
    func go2Delete(one:[String:Any]) {
        alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
            
            let pathArrs = url2PathOriParam(self.rootTemp.delete_url.unwrap)
            let pathDic = url2PathDic(mainDic: one,arr: pathArrs.comPa)
            
            
            KSNetwork.shared.doRequest(API.temp(.path(path: pathArrs.path, paramDic: pathDic))) { (data:BaseResult<OperateResult>) in
                if data.flag == TRUE {
                    KSToast("删除成功")
                    self.tableView.mj_header?.beginRefreshing()
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
            }
            
            
        })])
    }
    func go2Fantijiao(one:[String:Any]) {
        let pathArrs = url2PathOriParam(self.rootTemp.unrefer_url.unwrap)
        let pathDic = url2PathDic(mainDic: one,arr: pathArrs.comPa)
        
        
        var diccc = pathDic
        diccc.updateValue(self.rootTemp.is_auditFlow.unwrap, forKey: "is_audit")
        diccc.updateValue(self.rootTemp.flow_voucd.unwrap, forKey: "flow_voucd")
        diccc.updateValue(self.rootTemp.flow_flownm.unwrap, forKey: "flow_flownm")
        
        
        KSNetwork.shared.doRequest(API.temp(.path(path: pathArrs.path, paramDic: diccc))) { (data:BaseResult<OperateResult>) in
            if data.flag == TRUE {
                KSToast("成功")
                self.tableView.mj_header?.beginRefreshing()
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    func go2Tijiao(one:[String:Any]) {
        let pathArrs = url2PathOriParam(self.rootTemp.refer_url.unwrap)
        let pathDic = url2PathDic(mainDic: one,arr: pathArrs.comPa)
        
        
        var diccc = pathDic
        diccc.updateValue(self.rootTemp.is_auditFlow.unwrap, forKey: "is_audit")
        diccc.updateValue(self.rootTemp.flow_voucd.unwrap, forKey: "flow_voucd")
        diccc.updateValue(self.rootTemp.flow_flownm.unwrap, forKey: "flow_flownm")
        KSNetwork.shared.doRequest(API.temp(.path(path: pathArrs.path, paramDic: diccc))) { (data:BaseResult<OperateResult>) in
            if data.flag == TRUE {
                KSToast("成功")
                self.tableView.mj_header?.beginRefreshing()
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
        
    }
    func go2ModifyForm(_ indx:Int) {
        guard self.dataArray.count > indx else {
            KSToast("出错，稍后再试")
            return
        }
        let currentDic = self.dataArray[indx]
        if  self.rootTemp.webFormUrl != "" {
            let cwebV = SepWebVC()
            cwebV.refreshClosure = {
                self.tableView.mj_header?.beginRefreshing()
            }
            let uurl =  getUrl4ziding(str: self.rootTemp.webFormUrl, mainDic: currentDic)
            cwebV.reportUrl = uurl
            KSLog(uurl)
        
             cwebV.title = self.rootTemp.menu_nm
            self.navigationController?.pushViewController(cwebV, animated: true)
            
        } else {
            let view  = ConfigMenuForm(rootTemp: self.rootTemp, templateHandle: self.templateHandle, templateDic: self.templateDic)
            view.excuteType = .fix
            view.main = currentDic
            view.refreshClosure = {
                self.tableView.mj_header?.beginRefreshing()
            }
            self.navigationController?.pushViewController(view, animated: true)
        }
        
        
        
     
    }
    func go2web(url:String,title:String) {
        
        let cwebV = CommonWebController()
        cwebV.reportUrl = url
        cwebV.title = title
        self.navigationController?.pushViewController(cwebV, animated: true)
        
        
        
    }
    func performApi(url:String,one:[String:Any],titlex:String) {
        KSLog("pathArrs")
        let pathArrs = url2PathOriParam(url)
        KSLog(pathArrs)
        KSLog("-----------")
        var pathDic = url2PathDic(mainDic: one,arr: pathArrs.comPa)
        KSLog(pathDic)
        KSLog("-----------")
        let inputDic = pathDic.filter { $0.value.contains("i.") }
        
        KSLog(inputDic)
        if inputDic.count > 0 {
            
            var arr = [(String,String)]()
            for (key,value) in inputDic {
                arr.append((key,value))
            }
            let arrxx = arr.compactMap { onexx -> (String,String) in
                let sss =  onexx.1.replacingOccurrences(of: "i.", with: "").removeBrackets.removeDolendAt
                return (onexx.0,sss)
            }
            KSLog(arrxx)
            let vvv = ComAlertV()
            var opS = [nameBtnAction]()
            
            opS = [nameBtnAction(name: "确认", action: { _ in
                for xx in arrxx {
                    for yy in vvv.fieldArr {
                        if xx.1 == yy.0 {
                            pathDic.updateValue(yy.1.text.unwrap, forKey: xx.0)
                        }
                    }
                }
                
                vvv.dismiss()
                netW()
                
            }),nameBtnAction(name: "取消", action: { _ in
                vvv.dismiss()
            })]
            vvv.add(title: "输入", message: "",textFields:arrxx.compactMap {$0.1}, operateS: opS)
            vvv.present()
        } else {
            netW()
        }
        func netW () {
            KSNetwork.shared.doRequest(API.temp(.path(path: pathArrs.path, paramDic: pathDic))) { (data:BaseResult<OperateResult>) in
                if data.flag == TRUE {
                    KSToast("\(titlex)成功")
                    self.tableView.mj_header?.beginRefreshing()
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
            }
        }
        
        
        
    }
}

// MARK: -- 按钮控制
extension KSTempListVC {
    // 是否有提交按钮的逻辑
    func appendTijiao(one:[String:Any]) -> Bool {
        if rootTemp.refer_url.unwrap == "" {
            return false
        }
        if rootTemp.setModifyForbidden {
            return false
        }
        if fixedBtnControl(one:one,oriBtnName: "提交") == .agree {
            return true
        } else if fixedBtnControl(one:one,oriBtnName: "提交") == .disAgree {
            return false
        } else {
            if auditPaJudgeBtnC(one:one,oriBtnName: "提交") {
                return true
            } else {
                return false
            }
        }
        
    }
    func appendFanTijiao(one:[String:Any]) -> Bool {
        if rootTemp.unrefer_url.unwrap == "" {
            return false
        }
        if rootTemp.setModifyForbidden {
            return false
        }
        if fixedBtnControl(one:one,oriBtnName: "反提交") == .agree {
            return true
        } else if fixedBtnControl(one:one,oriBtnName: "反提交") == .disAgree {
            return false
        } else {
            if auditPaJudgeBtnC(one:one,oriBtnName: "反提交") {
                return true
            } else {
                return false
            }
        }
        
    }
    func appendDelete(one:[String:Any]) -> Bool {
        if rootTemp.delete_url.unwrap == "" {
            return false
        }
        if rootTemp.setModifyForbidden {
            return false
        }
        if fixedBtnControl(one:one,oriBtnName: "删除") == .agree {
            return true
        } else if fixedBtnControl(one:one,oriBtnName: "删除") == .disAgree {
            return false
        } else {
            if auditPaJudgeBtnC(one:one,oriBtnName: "删除") {
                return true
            } else {
                return false
            }
        }
    }
    
    func appendModify(one:[String:Any]) -> Bool {
        if rootTemp.save_url == "" {
            return false
        }
        if rootTemp.setModifyForbidden {
            return false
        }
        if fixedBtnControl(one:one,oriBtnName: "修改") == .agree {
            return true
        } else if fixedBtnControl(one:one,oriBtnName: "修改") == .disAgree {
            return false
        } else {
            if auditPaJudgeBtnC(one:one,oriBtnName: "修改") {
                return true
            } else {
                return false
            }
        }
    }
    func appendLiucheng(one:[String:Any]) -> Bool {
        
        if fixedBtnControl(one:one,oriBtnName: "流程图") == .agree {
            return true
        } else if fixedBtnControl(one:one,oriBtnName: "流程图") == .disAgree {
            return false
        } else {
            if auditPaJudgeBtnC(one:one,oriBtnName: "流程图") {
                return true
            } else {
                return false
            }
        }
    }
    // 审核字段控制 按钮
    func auditPaJudgeBtnC(one:[String:Any],oriBtnName:String) -> Bool {
        let auditF = any2Str(one[rootTemp.audit_field.unwrap])
        if oriBtnName == "流程图" {
            //  9  已提交状态
            if checkPlatform(type: .aoWang) || checkPlatform(type: .houQuan) {
                return (auditF == "9" && self.rootTemp.is_auditFlow == "1") || auditF == "1"
            } else {
                return auditF == "9" && self.rootTemp.is_auditFlow == "1"
            }
        }
        if oriBtnName == "删除" { // 0  未提交  2 已退回   空   4  提交失败
            return auditF  == "0" || auditF  == "2" || auditF  == "" || auditF  == "4"
        }
        if oriBtnName == "提交" { // 0  未提交  2 已退回   空  4  提交失败
            return auditF  == "0" || auditF  == "2" || auditF  == "4"
        }
        if oriBtnName == "反提交" {
            return auditF  == "9"
        }
        if oriBtnName == "修改" {
            return auditF  == "0" || auditF  == "2" || auditF  == "" || auditF  == "4"
        }
        return true
    }
    // setBtnShow是否对该按钮控制  返回该按钮 的显示隐藏
    func fixedBtnControl(one:[String:Any],oriBtnName:String) -> BtnJudgeStatus {
        // setBtnShow是否对该按钮控制
        var controlFlag:BtnJudgeStatus = .unControl
        // 固定按钮控制
        let saveVArr = rootTemp.grmmarArr.filter{ $0.contains(GrammarType.setBtnShow.rawValue) }
        for xxx in saveVArr {
            let arrrr = getKeyPara(xxx)
            if arrrr.first! == GrammarType.setBtnShow.rawValue {
                
                
                let sepA = arrrr[1].components(separatedBy: ":")
                if  sepA.count == 2 {
                    
                    let btnName = sepA[0]
                    if btnName == oriBtnName {
                        let condition = sepA[1]
                        
                        let boolFlag =  expressionReplace(condition,main:one, currDet: nil,rootTemp: rootTemp)
                        controlFlag = boolFlag ? .agree : .disAgree
                        
                        
                    }
                } else {
                    KSToast("setBtnShow 示例 \n setBtnShow@{删除:${auditmark}==0&&${auditmarkxx}==2}")
                }
                
                
            }
            
        }
        return controlFlag
    }
}
